export function parseUrlParams(params: string) {
    if (typeof params === 'undefined') return {}

    const obj: Record<string, any> = {}
    params.split('&').forEach(item => {
        const arr = item.split('=')
        if (arr.length === 2) {
            obj[arr[0]] = arr[1]
        }
    })
    return obj
}

export function getUrlParams() {
    if (typeof window === 'undefined') return {}
    const urlParams = window.location.href.split('?')[1]
    return parseUrlParams(urlParams)
}

/**
 * 下载文件
 * @param url 文件地址 
 * @param filename 文件名
 * @param cb 下载成功后回调函数
 */
export function downloadFile(url: string, filename: string, cb?: () => void) {
    if (typeof window === 'undefined') {
        throw new Error('请在浏览器环境中使用该方法')
    }

    const xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.responseType = 'blob'
    xhr.onload = function () {
        if (xhr.status === 200) {
            const link = document.createElement('a')
            const body: HTMLBodyElement = document.querySelector('body') as HTMLBodyElement

            link.href = window.URL.createObjectURL(xhr.response)
            link.download = filename

            // fix Firefox
            link.style.display = "none"
            body.appendChild(link)

            link.click()
            body.removeChild(link)

            window.URL.revokeObjectURL(link.href)
            cb?.()
        }
    }
    xhr.send()
}

export function setLocalStorage(key: string, value: any) {
    if (Object.prototype.toString.call(value) === "[object Array]" ||
        Object.prototype.toString.call(value) === "[object Object]") {
        value = JSON.stringify(value)
    }
    localStorage.setItem(key, value)
}

export function getLocalStorage(key: string, defaultValue?: any) {
    const value: string = localStorage.getItem(key) || ''
    // 处理布尔值
    if (value === 'true') return true
    if (value === 'false') return false

    // 处理其他类型
    let result
    try {
        result = JSON.parse(value)
    } catch (e) {
        result = value
    }

    // 处理数值类型
    // JSON.parse(123) 返回的是数值类型，转换为字符串
    if (typeof result === 'number') {
        result = String(result)
    }

    if (defaultValue && Object.prototype.toString.call(result) !== Object.prototype.toString.call(defaultValue)) {
        return defaultValue
    } else {
        return result
    }
}

export function setSessionStorage(key: string, value: any) {
    if (Object.prototype.toString.call(value) === "[object Array]" ||
        Object.prototype.toString.call(value) === "[object Object]") {
        value = JSON.stringify(value)
    }
    sessionStorage.setItem(key, value)
}

export function getSessionStorage(key: string, defaultValue?: any) {
    const value: string = sessionStorage.getItem(key) || ''
    // 处理布尔值
    if (value === 'true') return true
    if (value === 'false') return false

    // 处理其他类型
    let result
    try {
        result = JSON.parse(value)
    } catch (e) {
        result = value
    }

    // 处理数值类型
    // JSON.parse(123) 返回的是数值类型，转换为字符串
    if (typeof result === 'number') {
        result = String(result)
    }

    if (defaultValue && Object.prototype.toString.call(result) !== Object.prototype.toString.call(defaultValue)) {
        return defaultValue
    } else {
        return result
    }
}

/**
 * 全屏
 */
export function fullscreen(): Promise<void> {
    const element = document.documentElement
    if (element.requestFullscreen) {
        return element.requestFullscreen()
        // @ts-ignore
    } else if (element.msRequestFullscreen) {
        // @ts-ignore
        return element.msRequestFullscreen()
        // @ts-ignore
    } else if (element.mozRequestFullScreen) {
        // @ts-ignore
        return element.mozRequestFullScreen()
        // @ts-ignore
    } else if (element.webkitRequestFullscreen) {
        // @ts-ignore
        return element.webkitRequestFullscreen()
    } else {
        return Promise.reject('浏览器未找到全屏 Api')
    }
}

/**
 * 退出全屏
 */
export function exitFullscreen(): Promise<void> {
    if (document.exitFullscreen) {
        return document.exitFullscreen()
        // @ts-ignore
    } else if (document.msExitFullscreen) {
        // @ts-ignore
        return document.msExitFullscreen()
        // @ts-ignore
    } else if (document.mozCancelFullScreen) {
        // @ts-ignore
        return document.mozCancelFullScreen()
        // @ts-ignore
    } else if (document.webkitExitFullscreen) {
        // @ts-ignore
        return document.webkitExitFullscreen()
    } else {
        return Promise.reject('浏览器未找到全屏 Api')
    }
}

/**
 * 判断是否全屏展示
 */
export function isFullscreen(): boolean {
    return Boolean(
        document.fullscreenElement ||
        // @ts-ignore
        document.msFullscreenElement ||
        // @ts-ignore
        document.mozFullScreenElement ||
        // @ts-ignore
        document.webkitFullscreenElement) || false;
}

/**
 * 切换全屏/退出全屏
 */
export function toggleFullscreen(): void {
    if (isFullscreen()) {
        exitFullscreen()
    } else {
        fullscreen()
    }
}

/**
 * 获取 cookie
 */
export function getCookie(key: string): string {
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(key).replace(/[-.+*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1"))
}

/**
 * 设置 cookie
 */
export function setCookie(key: string, value: string, expires = 3600, path = '/', secure = false): boolean {
    if (!key || /^(?:expires|max\-age|path|domain|secure)$/i.test(key)) {
        return false
    }
    const expiresTime = new Date()
    expiresTime.setTime(expiresTime.getTime() + expires * 1000)
    const sExpires = '; expires=' + expiresTime.toUTCString()
    const domain = window.location.hostname
    document.cookie = encodeURIComponent(key) + '=' + encodeURIComponent(value) + sExpires + (domain ? '; domain=' + domain : '; path=') + (path ? '; path=' + path : '') + (secure ? '; secure' : '')
    return true
}

/**
 * 删除 cookie
 */
export function removeCookie(key: string, path = '/', domain = window.location.hostname): boolean {
    if (!key || !hasCookie(key)) { return false }
    document.cookie = encodeURIComponent(key) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (domain ? '; domain=' + domain : '') + (path ? '; path=' + path : '')
    return true
}

/**
 * 判断是否含有 cookie
 */
export function hasCookie(key: string): boolean {
    return (new RegExp('(?:^|;\\s*)' + encodeURIComponent(key).replace(/[-.+*]/g, '\\$&') + '\\s*\\=')).test(document.cookie)
}

export default {
    parseUrlParams,
    getUrlParams,
    downloadFile,
    setLocalStorage,
    getLocalStorage,
    setSessionStorage,
    getSessionStorage,
    fullscreen,
    exitFullscreen,
    isFullscreen,
    toggleFullscreen,
    getCookie,
    setCookie,
    removeCookie,
    hasCookie,
}